import React, { useEffect, useState } from "react";
import { Entypo, AntDesign, MaterialIcons } from "@expo/vector-icons";
import { Text, TouchableOpacity, View, StyleSheet } from "react-native";
import { Audio } from 'expo-av';
import AsyncStorage from "@react-native-async-storage/async-storage";
import Timer from "../components/Timer";
import SudokuBoard from "../components/SudokuBoard";
import NumberSelector from "../components/NumberSelector";
import NoteArea from "../components/NoteArea";
import Delete from "../components/Delete";
import Reload from "../components/Reload";
import Tips from "../components/Tips";
import Back from "../components/Back";
export default function Game_main({ navigation,route }) {
    const [selectedCell, setSelectedCell] = useState(null); //当前选中的单元格位置
    const [selectedNumber, setSelectedNumber] = useState(null);  //当前选中的数字
    const [selectedNote,setSelectedNote]=useState(null);  //当前选中的笔记数字
    //9x9 数独棋盘，每个单元格包含 value、noteValue、isFixed 和 isUserInput 属性
    const [board,setBoard]=useState(Array(9).fill().map(() => Array(9).fill({ value: null,noteValue:[], isFixed: false,isUserInput: false, isError:false })));
    const [wrongCells, setWrongCells] = useState([]);
    const [time, setTime] = useState(0);
    const [isRunning, setIsRunning] = useState(true);
    const { loadSavedGame } = route.params || { loadSavedGame: false };  //是否加载保存的棋盘
    const { level } = route.params || { level: 0 };
    const [errorCount, setErrorCount] = useState(0);
    const [solution,setSolution]=useState(null);
    const [history, setHistory] = useState([   //保存棋盘的历史记录
        board.map(row => row.map(cell => ({
            noteValue: [],
            value: cell.value,
            isFixed: cell.isFixed,
            isUserInput: cell.isUserInput
        })))
    ]);

    const [isSoundOn,setIsSoundOn]=useState(true);

    useEffect(()=>{
        const loadSettings=async()=>{
            try{
                const showIsSoundOn=await AsyncStorage.getItem('isSoundOn');
                if(showIsSoundOn!==null){
                    setIsSoundOn(JSON.parse(showIsSoundOn));
                }
            }catch(error){
                console.error("Error loading settings:",error);
            }
        }
        loadSettings();
    },[]);

    const playSound = async() => {
        const soundObject = new Audio.Sound();
        try{
            if(isSoundOn){
                await soundObject.loadAsync(require('../../resource/buttonSound.mp3'));
                await soundObject.replayAsync();
            }
        }catch(error){
            console.error("Error playing sound:",error);
        }
    }
    
    const handleStop = () => {
        setIsRunning(false);
        navigation.navigate("Game_stop",{board:board,errorCount:errorCount,solution:solution,time:time})
    };

    const handleNumberSelection = (number) => {
        setSelectedNumber(number);
        playSound();
        console.log(`Selected number: ${number}`);
    };
    const handleNoteSelection=(number)=>{
        setSelectedNote(number);
        playSound();
        console.log(`Selected notenumber: ${number}`);
    }
    const handleCellSelection = (rowkey, colkey) => {
        if(!board[rowkey][colkey].isFixed)
        setSelectedCell({ row: rowkey, col: colkey });
        playSound();
        console.log(`Selected cell: ${rowkey},${colkey}`);
    };
    const updateBoardHistory = (newBoard) => {
        setHistory(prevHistory => {
            const noteValuesCopy = newBoard.map(row =>
                row.map(cell => ({
                    noteValue: cell.noteValue ? [...cell.noteValue] : [],
                    value: cell.value,
                    isFixed: cell.isFixed,
                    isUserInput: cell.isUserInput
                }))
            );
            const lastHistory = prevHistory[prevHistory.length - 1];
            const hasChanged = JSON.stringify(noteValuesCopy) !== JSON.stringify(lastHistory);
            
            if (hasChanged) {
                return [...prevHistory, noteValuesCopy];
            }
            return prevHistory;
        });
    };

    useEffect(() => {
        let interval;
        if (isRunning) {
            interval = setInterval(() => {
                setTime(prevTime => prevTime + 1);
            }, 1000);
        }
        return () => clearInterval(interval);
    }, [isRunning]);
    
    //当 selectedNote 变化时，自动更新棋盘历史
    useEffect(() => {
        if (selectedNote) { 
            updateBoardHistory(board);
        }
    }, [selectedNote]);

    return (
        <View style={styles.container}>
            <View style={styles.timerContainer}>
                <Timer 
                    time={time}
                    setTime={setTime}
                    loadSavedGame={loadSavedGame}/>
            </View>
            <View style={styles.SudokuBoardContainer}>
                <SudokuBoard 
                selectedNumber={selectedNumber} 
                setSelectedNumber={setSelectedNumber} 
                selectedNote={selectedNote} 
                setSelectedNote={setSelectedNote} 
                board={board} setBoard={setBoard} 
                loadSavedGame={loadSavedGame} 
                selectedCell={selectedCell} 
                handleCellSelection={handleCellSelection}
                level={level}
                wrongCells={wrongCells}
                setWrongCells={setWrongCells}
                navigation={navigation}
                errorCount={errorCount}
                setErrorCount={setErrorCount}
                solution={solution}
                setSolution={setSolution}
                time={time}
                setTime={setTime}
                />
            </View>
            <View style={styles.fillContainer}>
                <NumberSelector onSelectedNum={handleNumberSelection} />
                <NoteArea onSelectedNote={handleNoteSelection} />
            </View>
            <View style={styles.toolbarContainer}>
                <Delete selectedCell={selectedCell} board={board} setBoard={setBoard} setWrongCells={setWrongCells}/>
                <Back history={history} setHistory={setHistory} setBoard={setBoard} />
                <Tips board={board} setBoard={setBoard} selectedCell={selectedCell} updateBoardHistory={updateBoardHistory}/>
                <Reload board={board} setBoard={setBoard} setWrongCells={setWrongCells}/>
                <TouchableOpacity 
                    onPress={() => {
                        handleStop();
                    }}
                >
                    <Entypo name="controller-paus" size={25} color="black" />
                </TouchableOpacity>
            </View>
            <View>
                <Text style={styles.wrongContainer}>错误: {errorCount}/3</Text>
            </View>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: "#f5f5f5",
        padding: 20,
    },
    fillContainer: {
        flexDirection: "row",
        justifyContent: "space-between",
        marginTop: 30,
        marginLeft: 20,
        marginRight: 20,
    },
    toolbarContainer: {
        flexDirection: "row",
        justifyContent: "space-between",
        marginTop: 30,
        marginLeft: 20,
        marginRight: 20,
    },
    wrongContainer: {
        fontSize: 15,
        color: "#black",
        textAlign: "center",
        marginTop: 10,
    },
    timerContainer: {
        marginTop: 10,
        marginBottom: 10,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    SudokuBoardContainer: {
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
});
